package top.yuan67.demo;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.generator.common.model.dto.GenerateParam;
import cloud.tianai.captcha.generator.common.model.dto.ImageCaptchaInfo;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.validator.ImageCaptchaValidator;
import io.netty.util.internal.ThreadLocalRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: NieQiang
 * @User: CAPTAIN
 * @CreateTime: 2023-8-29
 * @Desc: 验证码工具
 **/
@Component
public class CaptchaUtils {
  private static final Logger log = LoggerFactory.getLogger(CaptchaUtils.class);
  
  @Resource
  private ImageCaptchaApplication application;
  
  @Resource
  private RedisCache redisCache;
  
  public ImageCaptchaInfo genCaptcha(String username, String uuid) {
  
    // 生成证码的其中一个
    int typeKey = ThreadLocalRandom.current().nextInt(0, 5);
  
    String type;
    switch (typeKey){
      case 0:
        type = CaptchaTypeConstant.SLIDER;
        break;
      case 1:
        type = CaptchaTypeConstant.ROTATE;
        break;
      case 2:
        type = CaptchaTypeConstant.CONCAT;
        break;
      case 3:
        type = CaptchaTypeConstant.WORD_ORDER_IMAGE_CLICK;
        break;
      default:
        type = CaptchaTypeConstant.ROTATE_DEGREE;
        break;
    }
  
    log.info("验证码类型：{}", type);
    String verifyKey = Constants.CAPTCHA_CODE_KEY + username;
    GenerateParam param = new GenerateParam();
    param.setType(type);
    param.setBackgroundImageTag(null);
    param.setTemplateImageTag(null);
    param.setObfuscate(true);
    param.setShuffleImage(true);
    ImageCaptchaValidator imageCaptchaValidator = application.getImageCaptchaValidator();
    ImageCaptchaInfo imageCaptchaInfo = application.getImageCaptchaTemplate().generateCaptchaImage(param);
    Map<String, Object> map = imageCaptchaValidator.generateImageCaptchaValidData(imageCaptchaInfo);
    map.put(Constants.UUID, uuid);
    redisCache.setCacheObject(verifyKey, map, Constants.CAPTCHA_EXPIRATION, TimeUnit.SECONDS);
  
    // 打点日志记录
    return imageCaptchaInfo;
  }
}
